<template>
  <div>
    <div class="flex align-center justify-between margin">
      <span class="Gray_9e"
        >交互规则可以根据条件实时控制指定字段的显隐、是否可编辑、是否必填等属性。</span
      >
      <a-button type="primary" icon="plus" shape="round" @click="add"
        >添加交互</a-button
      >
    </div>

    <div class="flex flexColumn padding-sm">
      <div
        style="overflow: auto"
        :style="{ 'max-height': height + 'px' }"
        ref="sortableBox"
      >
        <eip-empty v-if="options && options.length == 0"></eip-empty>

        <div
          v-for="item in options"
          :key="item.id"
          class="ruleDrabItemContainer"
        >
          <div class="grabIcon drag-btn">
            <a-icon type="unordered-list" />
          </div>
          <div class="ruleItemCon">
            <div class="ruleNameInputBox">
              <input class="ruleNameInput text-eip" v-model="item.name" />
            </div>
            <span class="ruleItemTextRow" @click="editClick(item)"
              ><span class="leftLabel">当满足条件</span>
              <span class="rightLabel" :class="item.isFreeze ? 'Gray_bd' : ''"
                ><span
                  v-html="convertFiltersName(item.filters).slice(1, -1)"
                ></span
                ><span class="mLeft20 gray_9e">时</span></span
              >
            </span>

            <span
              @click="editClick(item)"
              class="ruleItemTextRow mTop10"
              v-for="(aitem, index) in item.actions"
              :key="index"
              ><span class="leftLabel">{{
                convertActionTypeName(aitem.type)
              }}</span
              ><span
                class="rightLabel WordBreak"
                :class="item.isFreeze ? 'Gray_bd' : ''"
              >
                {{ convertKeyName(aitem.key) }}</span
              ></span
            >

            <div class="ruleItemOptions">
              <a-icon
                type="check-square"
                @click="item.isFreeze = false"
                v-if="item.isFreeze"
              />

              <a-icon
                @click="item.isFreeze = true"
                type="check-square"
                v-if="!item.isFreeze"
                class="text-eip"
              />

              <a-icon type="copy" @click="copyClick(item)"></a-icon>
              <a-popconfirm
                placement="topRight"
                title="确定删除按钮?"
                ok-text="是"
                cancel-text="否"
                @confirm.stop="delClick(item)"
              >
                <a-icon style="color: red" type="delete"></a-icon>
              </a-popconfirm>
            </div>
          </div>
        </div>
      </div>
    </div>
    <edit
      ref="edit"
      :mode="edit.mode"
      v-if="edit.visible"
      :visible.sync="edit.visible"
      :zeroCodeId="zeroCodeId"
      :options="edit.options"
      @ok="editOk"
    ></edit>
  </div>
</template>
<script>
import edit from "./edit";
import { newGuid } from "@/utils/util";
import Sortable from "sortablejs";
export default {
  components: {
    edit,
  },
  data() {
    return {
      height: window.innerHeight - 130,
      edit: {
        visible: false,
        mode: "add",
        options: null,
      },
    };
  },
  props: {
    zeroCodeId: String,
    options: {
      type: Array,
    },
    columns: {
      type: Array,
    },
  },
  mounted() {
    this.rowDrop();
  },
  methods: {
    /**
     * 拖拽
     */
    rowDrop() {
      let that = this;

      this.$nextTick(() => {
        const sortableBox = this.$refs.sortableBox;
        if (sortableBox) {
          Sortable.create(sortableBox, {
            handle: ".drag-btn",
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = that.options.splice(oldIndex, 1)[0];
              that.options.splice(newIndex, 0, currRow);
            },
          });
        }
      });
    },
    add() {
      this.edit.mode = "add";
      this.edit.visible = true;
    },

    /**
     *
     */
    editClick(form) {
      this.edit.visible = true;
      this.edit.options = form;
      this.edit.mode = "edit";
    },

    /**
     *
     * @param form
     */
    editOk(form) {
      //是否已有
      let that = this;
      if (this.edit.mode == "add") {
        this.options.push(form);
      } else {
        let number = 0;
        this.options.forEach((item, index) => {
          if (item.id == form.id) {
            number = index;
          }
        });
        that.options.splice(number, 1, form);
      }

      this.rowDrop();
    },
    /**
     * 删除
     * @param item
     */
    delClick(form) {
      this.$utils.remove(this.options, (f) => f.id == form.id);
    },
    /**
     *复制
     */
    copyClick(form) {
      var copy = this.$utils.clone(form, true);
      copy.id = newGuid();
      copy.name += "-复制";
      this.options.push(copy);
    },
    /**
     * 转换为名称
     */
    convertActionTypeName(type) {
      switch (type) {
        case this.eipZeroCodeFormSettingRuleActionType.show:
          return "显示";
        case this.eipZeroCodeFormSettingRuleActionType.hide:
          return "隐藏";
        case this.eipZeroCodeFormSettingRuleActionType.write:
          return "可编辑";
        case this.eipZeroCodeFormSettingRuleActionType.readonly:
          return "只读";
        case this.eipZeroCodeFormSettingRuleActionType.required:
          return "必填";
        case this.eipZeroCodeFormSettingRuleActionType.readonlyAll:
          return "只读所有字段";
      }
    },

    /**
     * 转换为名称
     */
    convertKeyName(key) {
      if (key) {
        var keyAll = this.columns.filter((f) => key.includes(f.key));
        return keyAll.map((m) => m.label).join("，");
      }
      return "";
    },

    /**
     * 生成判断Js
     */
    convertFiltersName(filter) {
      let that = this;
      var js = "";
      var isFirst = true;
      //处理字段查询明细
      if (filter.rules != null && filter.rules.length > 0) {
        filter.rules.forEach((item) => {
          if (item.field && item.op) {
            if (isFirst != true) {
              js +=
                "<label class='text-eip text-bold'>" +
                (filter.groupOp == "AND" ? " 且 " : " 或 ") +
                "</label>";
            }
            js += that.convertFilters(item);
            isFirst = false;
          }
        });
      }

      //处理嵌套查询
      if (filter.groups != null && filter.groups.length > 0) {
        filter.groups.forEach((item) => {
          var child = that.convertFiltersName(item);
          if (child) {
            if (isFirst != true) {
              //非首个条件添加AND或者OR
              js +=
                "<label class='text-eip text-bold'>" +
                (filter.groupOp == "AND" ? " 且 " : " 或 ") +
                "</label>";
            }
            js += child;
            isFirst = false;
          }
        });
      }
      return js.length > 0 ? "(" + js + ")" : "";
    },

    /// <summary>
    /// 处理单个字段查询，匹配数据类型及查询方式
    /// </summary>
    /// <param name="rule">查询字段对象</param>
    /// <returns></returns>
    convertFilters(rule) {
      if (rule.op && rule.field) {
        //Sql注入替换后数据
        var data = rule.data;
        var searchCase = "";
        var column = this.$utils.find(this.columns, (f) => f.key == rule.field);
        if (column) {
          //如果是动态值
          if (rule.opType == this.eipZeroCodeFormSettingOpType.variable) {
            var variable = this.$utils.find(
              this.columns,
              (f) => f.key == rule.data
            );
            if (variable) {
              data = variable.label;
            }
          } else {
            switch (column.type) {
              case this.eipZeroCodeControl.correlation:
                break;
              case this.eipZeroCodeControl.select:
              case this.eipZeroCodeControl.radio:
              case this.eipZeroCodeControl.checkbox:
                if (data) {
                  data = column.options.options
                    .filter((f) => data.includes(f.value))
                    .map((m) => m.label)
                    .join(",");
                } else {
                  data = "";
                }
                break;
              case this.eipZeroCodeControl.rate:
                if (data) {
                  var values = [];
                  for (let index = 0; index < data.length; index++) {
                    var value = data[index];
                    values.push(value + "星");
                  }
                  data = values.join(",");
                } else {
                  data = "";
                }
                break;
              case this.eipZeroCodeControl.switch:
                data = data == 1 ? "开启" : "关闭";
                break;
              case this.eipZeroCodeControl.uploadFile:
              case this.eipZeroCodeControl.uploadImg:
                data = data == 1 ? "有" : "无";
                break;
            }
          }

          switch (rule.op) {
            case "eq": //等于
              searchCase += this.getFilter(column.label, " 等于 " + data + "");
              break;
            case "eqphone": //等于
              searchCase += this.getFilter(
                column.label,
                " 不等于 " + data + ""
              );
              break;
            case "ne": //不等于
              searchCase += this.getFilter(
                column.label,
                " 不等于 " + data + ""
              );
              break;
            case "bw": //以...开始
              break;
            case "bn": //不以...开始
              break;
            case "ew": //结束于
              break;
            case "en": //不结束于
              break;
            case "lt": //小于
              break;
            case "le": //小于等于
              break;
            case "gt": //大于
              break;
            case "ge": //大于等于
              break;
            case "in": //包括
              break;
            case "ni": //不包含
              break;
            case "cn": //包含
              searchCase += this.getFilter(column.label, " 包含 " + data + "");
              break;
            case "nc": //不包含
              searchCase += this.getFilter(
                column.label,
                " 不包含 " + data + ""
              );
              break;
            case "nu": //空值
              searchCase += this.getFilter(column.label, " 为空 ");
              break;
            case "nn": //非空值
              searchCase += this.getFilter(column.label, " 不为空 ");
              break;
            case "dateeq": //时间等于
              break;
            case "datelt": //小于
              break;
            case "datele": //小于等于
              break;
            case "dategt": //大于
              break;
            case "datege": //大于等于
              break;
            case "daterange": //针对时间特别处理
              break;
            case "jcn": //包含
              break;
          }
          return searchCase;
        } else {
          return "表达式异常";
        }
      }
      return "";
    },

    /// <summary>
    /// 转换
    /// </summary>
    /// <param name="field"></param>
    /// <param name="formula"></param>
    /// <returns></returns>
    getFilter(field, formula) {
      var search = "";
      var searchCase = "";
      var split = field.split(",");
      if (split.length > 1) {
        field.split(",").forEach((fi) => {
          search += fi + formula + " 或 " /* " like '%" + data + "%' OR "*/;
        });

        searchCase += "(" + search.substring(0, search.length - 4) + ")";
      } else {
        searchCase += field + formula;
      }
      return searchCase;
    },
  },
};
</script>
<style scoped>
.flex {
  flex: 1;
}
.flexColumn {
  display: flex;
  flex-direction: column;
}
.Gray_9e {
  color: #9e9e9e !important;
}

.ruleDrabItemContainer {
  align-items: center;
  cursor: grab;
  display: flex;
  opacity: 1 !important;
  visibility: visible !important;
}

.ruleDrabItemContainer:hover .grabIcon {
  visibility: visible;
}

.ruleDrabItemContainer .grabIcon {
  height: 36px;
  line-height: 36px;
  margin-right: 3px;
  margin-top: 18px;
  text-align: center;
  visibility: hidden;
  width: 18px;
}

.ruleDrabItemContainer .grabIcon .icon {
  color: #9e9e9e;
}

.ruleItemCon {
  border-radius: 5px;
  box-shadow: inset 0 0 0 1px #eaeaea;
  box-sizing: border-box;
  cursor: pointer;
  display: flex;
  flex: 1;
  flex-direction: column;
  margin-top: 26px;
  min-width: 0;
  padding: 14px 24px;
  position: relative;
  width: 100%;
}

.ruleItemCon:hover {
  box-shadow: inset 0 0 0 2px #eaeaea;
}

.ruleItemCon:hover .ruleItemOptions {
  visibility: visible;
}

.ruleItemCon.active {
  box-shadow: inset 0 0 0 2px #2196f3;
}

.ruleItemCon.active .ruleItemOptions {
  visibility: visible;
}

.ruleItemCon .gray_9e {
  color: #9e9e9e;
}

.ruleItemCon .ruleItemOptions {
  align-items: center;
  background: #fff;
  border: 1px solid #eaeaea;
  border-radius: 17px;
  display: flex;
  height: 32px;
  justify-content: space-around;
  position: absolute;
  right: 12px;
  top: -16px;
  visibility: hidden;
  width: 117px;
  z-index: 2;
}

.ruleItemCon .ruleItemOptions .RedHover:hover {
  color: #db493f;
}

.ruleItemCon .ruleNameInputBox {
  background: #fff;
  box-sizing: border-box;
  height: 20px;
  left: 12px;
  padding: 0 10px;
  position: absolute;
  top: -10px;
}

.ruleItemCon .ruleNameInput {
  border: none;
  border-bottom: 1px solid transparent;
  font-weight: 700;
  height: 100%;
}

.ruleItemCon .ruleNameInput:hover {
  border-bottom: 1px dashed #bdbdbd;
}

.ruleItemCon .ruleNameInput:focus {
  border-bottom: 1px solid #2196f3 !important;
}

.ruleItemCon .ruleItemTextRow {
  display: flex;
}

.ruleItemCon .ruleItemTextRow .leftLabel {
  color: #9e9e9e;
  margin-right: 20px;
  text-align: right;
  width: 85px;
}

.ruleItemCon .ruleItemTextRow .rightLabel {
  color: #333;
  flex: 1;
  min-width: 0;
}

.DropdownDeleteRuleTrigger {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.24);
  font-size: 14px;
  padding: 20px;
  width: 320px;
}

.DropdownDeleteRuleTrigger .title {
  color: #f51744;
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 32px;
}

.DropdownDeleteRuleTrigger .deleteGroupBtns {
  align-items: center;
  display: flex;
  justify-content: flex-end;
}

.DropdownDeleteRuleTrigger .deleteGroupBtns .deleteBtn {
  background: #f51744;
  border-radius: 2px;
  color: #fff;
  cursor: pointer;
  height: 28px;
  line-height: 28px;
  margin-left: 37px;
  text-align: center;
  width: 70px;
}

.DropdownDeleteRuleTrigger .deleteGroupBtns .deleteBtn:hover {
  background-color: #f44336;
}

.ruleFilterColumnOptionList {
  border-radius: 2px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.24);
  max-height: 270px;
  min-height: 100px;
  overflow-x: hidden;
  position: static;
  width: 314px;
}

.ruleFilterColumnOptionList .Menu {
  border-radius: 0;
  box-shadow: none;
  position: relative;
  width: 314px;
}

.ruleFilterColumnOptionList .Menu .Item-content {
  padding: 0 15px;
}

.ruleFilterColumnOptionList .Menu .Item-content .icon {
  color: #9e9e9e;
  font-size: 14px;
  margin-right: 10px;
  vertical-align: middle;
}

.ruleFilterColumnOptionList .Menu .Item-content > span {
  vertical-align: middle;
}

.ruleFilterColumnOptionList .ruleSearchWrap {
  background: #fff !important;
  position: relative;
}

.ruleFilterColumnOptionList .ruleSearchWrap input {
  border: none;
  border-bottom: 1px solid #f5f5f5;
  box-sizing: border-box;
  height: 41px;
  padding: 0 16px 0 35px;
  width: 100%;
}

.ruleFilterColumnOptionList .ruleSearchWrap input:focus {
  border-color: #f5f5f5 !important;
}

.ruleFilterColumnOptionList .ruleSearchWrap input::-webkit-input-placeholder {
  color: #bdbdbd;
}

.ruleFilterColumnOptionList .ruleSearchWrap input::-moz-placeholder {
  color: #bdbdbd;
}

.ruleFilterColumnOptionList .ruleSearchWrap input::-ms-input-placeholder {
  color: #bdbdbd;
}

.ruleFilterColumnOptionList .ruleSearchWrap .icon {
  position: absolute;
  top: 13px;
}

.ruleFilterColumnOptionList .ruleSearchWrap .search {
  left: 15px;
}

.ruleFilterColumnOptionList .ruleSearchWrap .close {
  color: #bdbdbd;
  right: 15px;
}

.ruleFilterColumnOptionList .ruleSearchWrap .close:hover {
  color: #757575;
}

.ruleFilterColumnOptionList .ming.Item .Item-content:hover .icon {
  color: #fff !important;
}

.ruleListSelectDropdown
  .ant-select-item-option-selected:not(.ant-select-item-option-disabled) {
  background-color: #2196f3 !important;
  color: #fff !important;
  font-weight: 400 !important;
}

.ruleListSelectDropdown.ant-select-focused:not(
    .ant-select-disabled
  ).ant-select-single:not(.ant-select-customize-input)
  .ant-select-selector,
.ruleListSelectDropdown.ant-select:not(.ant-select-disabled):hover
  .ant-select-selector {
  border-color: #2196f3 !important;
}

.addConditionTrigger {
  background: #fff;
  border-radius: 2px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.24);
  color: #333;
  display: flex;
  flex-direction: column;
  font-weight: 400;
  margin-bottom: 10px;
  padding: 8px 0;
  width: 160px;
}

.addConditionTrigger div {
  align-items: center;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  line-height: 36px;
  padding: 0 15px;
}

.addConditionTrigger div:hover {
  background: #f5f5f5;
}

.addConditionTrigger.rc-trigger-popup-hidden {
  display: none !important;
}
.mLeft5 {
  margin-left: 5px !important;
}
.mRight5 {
  margin-right: 5px !important;
}
.ruleItemCon .gray_9e {
  color: #9e9e9e;
}

.mLeft20 {
  margin-left: 20px !important;
}

.Gray_bd {
  color: #bdbdbd !important;
}
</style>
